import React, { useState, useRef, useCallback, useEffect } from 'react';
import clsx from 'clsx';
import { SearchOutlined, AudioOutlined, CameraOutlined, CloseOutlined } from '@ant-design/icons';
import type { SearchInputProps } from '@/types';
import { useDebounce } from '@/hooks/useDebounce';
import { Button } from '@/components/common/Button';
import { SearchSuggestions } from '../SearchSuggestions';
import styles from './SearchInput.module.css';

/**
 * 搜索输入组件
 */
export const SearchInput: React.FC<SearchInputProps> = ({
  placeholder = '搜索任何内容...',
  value,
  defaultValue = '',
  onSearch,
  onSuggestionSelect,
  onChange,
  onFocus,
  onBlur,
  suggestions = [],
  loading = false,
  disabled = false,
  enableVoiceSearch = false,
  enableImageSearch = false,
  debounceMs = 300,
  maxLength = 500,
  autoFocus = false,
  clearable = true,
  size = 'medium',
  className,
  testId,
  ...props
}) => {
  // 状态管理
  const [inputValue, setInputValue] = useState(value || defaultValue);
  const [isFocused, setIsFocused] = useState(false);
  const [showSuggestions, setShowSuggestions] = useState(false);
  const [selectedIndex, setSelectedIndex] = useState(-1);
  
  // 引用
  const inputRef = useRef<HTMLInputElement>(null);
  const containerRef = useRef<HTMLDivElement>(null);
  
  // 防抖处理
  const debouncedValue = useDebounce(inputValue, debounceMs);
  
  // 受控组件处理
  const currentValue = value !== undefined ? value : inputValue;
  
  // 防抖后触发搜索建议
  useEffect(() => {
    if (debouncedValue && debouncedValue.trim() && isFocused) {
      onChange?.(debouncedValue);
    }
  }, [debouncedValue, onChange, isFocused]);
  
  // 显示建议面板
  useEffect(() => {
    setShowSuggestions(isFocused && suggestions.length > 0);
  }, [isFocused, suggestions.length]);
  
  // 自动聚焦
  useEffect(() => {
    if (autoFocus && inputRef.current) {
      inputRef.current.focus();
    }
  }, [autoFocus]);
  
  // 处理输入变化
  const handleInputChange = useCallback((e: React.ChangeEvent<HTMLInputElement>) => {
    const newValue = e.target.value;
    
    if (value === undefined) {
      setInputValue(newValue);
    }
    
    onChange?.(newValue);
    setSelectedIndex(-1);
  }, [value, onChange]);
  
  // 处理键盘事件
  const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLInputElement>) => {
    switch (e.key) {
      case 'Enter':
        e.preventDefault();
        if (selectedIndex >= 0 && suggestions[selectedIndex]) {
          // 选择建议项
          const suggestion = suggestions[selectedIndex];
          onSuggestionSelect?.(suggestion);
          setShowSuggestions(false);
        } else {
          // 执行搜索
          onSearch(currentValue);
          setShowSuggestions(false);
        }
        break;
        
      case 'ArrowDown':
        e.preventDefault();
        setSelectedIndex(prev => 
          prev < suggestions.length - 1 ? prev + 1 : prev
        );
        break;
        
      case 'ArrowUp':
        e.preventDefault();
        setSelectedIndex(prev => prev > -1 ? prev - 1 : -1);
        break;
        
      case 'Escape':
        setShowSuggestions(false);
        setSelectedIndex(-1);
        inputRef.current?.blur();
        break;
        
      case 'Tab':
        if (showSuggestions) {
          setShowSuggestions(false);
        }
        break;
    }
  }, [selectedIndex, suggestions, onSuggestionSelect, onSearch, currentValue, showSuggestions]);
  
  // 处理焦点
  const handleFocus = useCallback((e: React.FocusEvent<HTMLInputElement>) => {
    setIsFocused(true);
    onFocus?.(e);
  }, [onFocus]);
  
  // 处理失焦
  const handleBlur = useCallback((e: React.FocusEvent<HTMLInputElement>) => {
    // 延迟隐藏建议，允许点击建议项
    setTimeout(() => {
      setIsFocused(false);
      setShowSuggestions(false);
      setSelectedIndex(-1);
    }, 200);
    
    onBlur?.(e);
  }, [onBlur]);
  
  // 处理建议选择
  const handleSuggestionSelect = useCallback((suggestion: any) => {
    onSuggestionSelect?.(suggestion);
    setShowSuggestions(false);
    setSelectedIndex(-1);
    inputRef.current?.focus();
  }, [onSuggestionSelect]);
  
  // 清除输入
  const handleClear = useCallback(() => {
    const newValue = '';
    if (value === undefined) {
      setInputValue(newValue);
    }
    onChange?.(newValue);
    inputRef.current?.focus();
  }, [value, onChange]);
  
  // 语音搜索
  const handleVoiceSearch = useCallback(() => {
    // TODO: 实现语音搜索功能
    console.log('Voice search clicked');
  }, []);
  
  // 图片搜索
  const handleImageSearch = useCallback(() => {
    // TODO: 实现图片搜索功能
    console.log('Image search clicked');
  }, []);
  
  // 构建样式类名
  const containerClasses = clsx(
    styles.container,
    styles[`container--${size}`],
    {
      [styles['container--focused']]: isFocused,
      [styles['container--disabled']]: disabled,
      [styles['container--loading']]: loading,
    },
    className
  );
  
  return (
    <div ref={containerRef} className={containerClasses} data-testid={testId}>
      <div className={styles.inputWrapper}>
        {/* 搜索图标 */}
        <div className={styles.searchIcon}>
          <SearchOutlined />
        </div>
        
        {/* 输入框 */}
        <input
          ref={inputRef}
          type="text"
          className={styles.input}
          placeholder={placeholder}
          value={currentValue}
          onChange={handleInputChange}
          onKeyDown={handleKeyDown}
          onFocus={handleFocus}
          onBlur={handleBlur}
          disabled={disabled}
          maxLength={maxLength}
          autoComplete="off"
          spellCheck="false"
          {...props}
        />
        
        {/* 操作按钮区域 */}
        <div className={styles.actions}>
          {/* 清除按钮 */}
          {clearable && currentValue && (
            <Button
              variant="secondary"
              size="small"
              icon={<CloseOutlined />}
              onClick={handleClear}
              className={styles.actionButton}
              aria-label="清除搜索"
            />
          )}
          
          {/* 语音搜索按钮 */}
          {enableVoiceSearch && (
            <Button
              variant="secondary"
              size="small"
              icon={<AudioOutlined />}
              onClick={handleVoiceSearch}
              className={styles.actionButton}
              aria-label="语音搜索"
            />
          )}
          
          {/* 图片搜索按钮 */}
          {enableImageSearch && (
            <Button
              variant="secondary"
              size="small"
              icon={<CameraOutlined />}
              onClick={handleImageSearch}
              className={styles.actionButton}
              aria-label="图片搜索"
            />
          )}
          
          {/* 搜索按钮 */}
          <Button
            variant="primary"
            size={size}
            loading={loading}
            onClick={() => onSearch(currentValue)}
            className={styles.searchButton}
            aria-label="搜索"
          >
            搜索
          </Button>
        </div>
      </div>
      
      {/* 搜索建议 */}
      {showSuggestions && (
        <SearchSuggestions
          suggestions={suggestions}
          onSelect={handleSuggestionSelect}
          selectedIndex={selectedIndex}
          highlightQuery={currentValue}
          className={styles.suggestions}
        />
      )}
    </div>
  );
};

export default SearchInput;
